package com.aliang.shopping.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliang.shopping.common.Result;
import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.config.OssConfig;
import com.aliang.shopping.contact.ResultMsgContact;
import com.aliang.shopping.exception.DataException;
import com.aliang.shopping.log.annotation.OperateLog;
import com.aliang.shopping.log.enums.OperateType;
import com.aliang.shopping.model.converter.GoodsSkuConverter;
import com.aliang.shopping.model.dto.common.UpdateStatusDTO;
import com.aliang.shopping.model.dto.goodsSku.GoodsSkuInsertDTO;
import com.aliang.shopping.model.dto.goodsSku.GoodsSkuUpdateDTO;
import com.aliang.shopping.model.enums.UserTypeEnum;
import com.aliang.shopping.model.po.GoodsSku;
import com.aliang.shopping.model.po.GoodsSpec;
import com.aliang.shopping.model.vo.goods.GoodsSkuVO;
import com.aliang.shopping.security.Auth;
import com.aliang.shopping.security.PreventRepeatSubmit;
import com.aliang.shopping.service.GoodsSkuService;
import com.aliang.shopping.service.GoodsSpecService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/goodsSku")
@AllArgsConstructor
public class GoodsSkuController {

    private final GoodsSkuService goodsSkuService;
    private final GoodsSkuConverter goodsSkuConverter;
    private final GoodsSpecService goodsSpecService;
    private final OssConfig ossConfig;

    /**
     * 商品SKU信息插入
     *
     * @param insertDTO
     * @return
     */
    @PostMapping("/insert")
    @ApiOperation("商品SKU信息插入")
    @PreventRepeatSubmit
    @OperateLog(title = "商品SKU信息插入", type = OperateType.INSERT)
    @Auth(role = UserTypeEnum.BUSINESS)
    @Transactional
    public Result<String> insertGoodsSku(@RequestBody GoodsSkuInsertDTO insertDTO) {
        //数据不能为空
        if (BeanUtil.hasNullField(insertDTO)
                || insertDTO.getSpecList().isEmpty()
                || insertDTO.getPrice().doubleValue() <= 0
                || insertDTO.getGoodsId() == 0
        ) {
            throw new DataException(ResultCodeEnum.DATA_LACK);
        }
        // 如有图片，则截取图片地址
        if (StrUtil.isNotBlank(insertDTO.getImage())) {
            insertDTO.setImage(StrUtil.subAfter(insertDTO.getImage(), ossConfig.getUrl(), false));
        }
        //数据转化
        GoodsSku poByInsertDTO = this.goodsSkuConverter.toPoByInsertDTO(insertDTO);

        // 保存数据
        boolean save = this.goodsSkuService.save(poByInsertDTO);
        if (!save) {
            return Result.fail(ResultMsgContact.INSERT_FAIL);
        }
        return Result.ok(ResultMsgContact.INSERT_SUCCESS);
    }

    /**
     * 商品SKU信息删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/del")
    @ApiOperation("商品SKU信息删除")
    @PreventRepeatSubmit
    @OperateLog(title = "商品SKU信息删除", type = OperateType.DELETE)
    @Transactional
    @Auth(role = UserTypeEnum.BUSINESS)
    public Result<String> delGoodsSku(@RequestBody List<Long> ids) {
        boolean removeByIds = this.goodsSkuService.removeByIds(ids);
        // 删除失败
        if (!removeByIds) {
            return Result.fail(ResultMsgContact.DELETE_FAIL);
        }
        return Result.ok(ResultMsgContact.DELETE_SUCCESS);
    }

    /**
     * 商品SKU信息更改
     *
     * @param updateDTO
     * @return
     */
    @PutMapping("/update")
    @ApiOperation("商品SKU信息更改")
    @PreventRepeatSubmit
    @OperateLog(title = "商品SKU信息更改", type = OperateType.UPDATE)
    @Auth(role = UserTypeEnum.BUSINESS)
    @Transactional
    public Result<String> updateGoodsSku(@RequestBody GoodsSkuUpdateDTO updateDTO) {
        //数据不能为空
        if (BeanUtil.hasNullField(updateDTO)
                || updateDTO.getId() <= 0
                || updateDTO.getSpecList().isEmpty()
                || updateDTO.getPrice().doubleValue() <= 0
                || updateDTO.getGoodsId() == 0
        ) {
            throw new DataException(ResultCodeEnum.DATA_LACK);
        }
        // 如有图片，则截取图片地址
        if (StrUtil.isNotBlank(updateDTO.getImage())) {
            updateDTO.setImage(StrUtil.subAfter(updateDTO.getImage(), ossConfig.getUrl(), false));
        }
        //转换数据
        GoodsSku goodsSku = this.goodsSkuConverter.toPoByUpdateDTO(updateDTO);

        //保存数据
        this.goodsSkuService.updateById(goodsSku);
        return Result.ok(ResultMsgContact.UPDATE_SUCCESS);
    }

    /**
     * 商品SKU信息状态更改
     *
     * @param updateDTO
     * @return
     */
    @PutMapping("/update_static")
    @ApiOperation("商品SKU信息状态更改")
    @PreventRepeatSubmit
    @OperateLog(title = "商品SKU信息状态更改", type = OperateType.UPDATE_STATUS)
    @Auth(role = UserTypeEnum.BUSINESS)
    public Result<String> updateGoodsSkuStatic(@RequestBody UpdateStatusDTO updateDTO) {
        //必要字段非空校验
        if (BeanUtil.isEmpty(updateDTO)
        ) {
            throw new DataException(ResultCodeEnum.DATA_LACK);
        }
        // 如果是上架，需要检查规格数是否一致
        if (updateDTO.getStatus() == 1) {
            GoodsSku one = this.goodsSkuService.getOne(new LambdaQueryWrapper<GoodsSku>()
                    .select(GoodsSku::getGoodsId,GoodsSku::getSpecList) // 查询规格
                    .eq(GoodsSku::getId, updateDTO.getId()) // 根据id查询
            );
            // 获取该商品sku的规格数据
            List<Long> specIds = JSONUtil.toList(one.getSpecList(), Long.class);
            // 获取该商品的父规格数量
            int count = this.goodsSpecService.count(new LambdaQueryWrapper<GoodsSpec>()
                    .eq(GoodsSpec::getGoodsId, one.getGoodsId()) // 根据商品id查询
                    .eq(GoodsSpec::getParentId, 0) //父规格的父Id为0
            );
            // 数量不一致。抛出异常
            if (specIds.size() != count) {
                throw new DataException(ResultCodeEnum.GOODS_SPEC_NUM_ERROR);
            }
        }
        //转换数据
        GoodsSku goodsSku = this.goodsSkuConverter.toPoByUpdateStaticDTO(updateDTO);
        //更新数据
        this.goodsSkuService.updateById(goodsSku);
        return Result.ok(ResultMsgContact.UPDATE_SUCCESS);
    }

    /**
     * 商品SKU信息分页搜索
     */
    @GetMapping("/getGoodsSkuAll/{goodsId}")
    @ApiOperation("商品SKU信息搜索")
    public Result<List<GoodsSkuVO>> getGoodsSkuAll(@PathVariable("goodsId") Long goodsId) {
        List<GoodsSku> list = this.goodsSkuService.list(
                new LambdaQueryWrapper<GoodsSku>()
                        .eq(GoodsSku::getGoodsId, goodsId)
        );
        List<GoodsSkuVO> voList = this.goodsSkuConverter.toVoList(list);
        voList.forEach(vo -> {
            //图片不为空，设置完整路径
            if (StrUtil.isNotBlank(vo.getImage())) {
                vo.setImage(ossConfig.getUrl() + vo.getImage());
            }
        });
        return Result.ok(voList);
    }


}
